package com.haomin.terra_cotta_warriors.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.haomin.terra_cotta_warriors.data_object.ParClass;
import com.haomin.terra_cotta_warriors.data_object.Question;
import com.haomin.terra_cotta_warriors.data_object.SonClass;
import com.haomin.terra_cotta_warriors.repository.PerClassRepo;
import com.haomin.terra_cotta_warriors.repository.QuestionsRepo;
import com.haomin.terra_cotta_warriors.repository.SonClassRepo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

/**
 * @author haomin
 * @date 2022/11/16 17:04
 **/

@Slf4j
public class Service {
    private final PerClassRepo perClassRepo;
    private final SonClassRepo sonClassRepo;
    private final QuestionsRepo questionsRepo;

        // 持久化保存
    private final ObjectMapper objectMapper;

    @Autowired
    public Service(PerClassRepo perClassRepo, SonClassRepo sonClassRepo, QuestionsRepo questionsRepo, ObjectMapper objectMapper) {
        this.perClassRepo = perClassRepo;
        this.sonClassRepo = sonClassRepo;
        this.questionsRepo = questionsRepo;
        this.objectMapper = objectMapper;
    }

    class sonAndQ {
        public String sname;
        public List<Question> list;

        public sonAndQ(String sname, List<Question> list) {
            this.sname = sname;
            this.list = list;
        }
    }

    class PerAndS {
        public String pname;
        public List<sonAndQ> list;

        public PerAndS(String pname, List<sonAndQ> list) {
            this.pname = pname;
            this.list = list;
        }
    }
    public void save1() throws IOException {
        List<ParClass> list = perClassRepo.selectAll();
        List<PerAndS> perAndSList = new LinkedList<>();
        for (int i = 0; i < list.size(); i++) {
            ParClass parClass = list.get(i);
            List<SonClass> sonClasses = sonClassRepo.selectBiyPid(parClass.pid);

            List<sonAndQ> sonAndQList = new LinkedList<>();
            for (int j = 0; j < sonClasses.size(); j++) {
                SonClass sonClass = sonClasses.get(j);
                List<Question> questions = questionsRepo.selectBiyQid(sonClass.sid);

                sonAndQ sonAndQ = new sonAndQ(sonClass.sname, questions);
                sonAndQList.add(sonAndQ);
            }
            PerAndS perAndS = new PerAndS(parClass.pname, sonAndQList);
            perAndSList.add(perAndS);
        }
        File forwardFile = new File("C:\\Users\\86187\\Desktop\\机设", "forward.json");
        objectMapper.writeValue(forwardFile, perAndSList);
        log.debug("保存json结束{}", forwardFile.getCanonicalPath());
    }
}